package com.qf.servlet;

import com.alibaba.druid.util.StringUtils;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 29125
 * @version V1.0
 * @Project java2203
 * @Package com.qf.servlet
 * @Description:
 * @Date 2022/5/27 13:26
 */
@WebServlet("/login")
public class LoginServlet extends BaseServlet {
    //注册
    public void check(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取参数
        String username = request.getParameter("username");
        //调用service层方法，判断用户是否可用
        UserService userService=new UserServiceImpl();
        boolean check = userService.check(username);

        return;
    }

    //登录
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //用户名有中文，避免出现乱码
        request.setCharacterEncoding("utf-8");//request获取用户需求的语句用utf-8
        response.setContentType("text/html;charset=utf-8");//response处理用户请求，将文档/页面用utf-8
        //1获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //非空验证  调用StringUtil下的方法  创建StringUtil
        if (StringUtils.isEmpty(username)) {
            response.getWriter().write("用户名不能为空");
            return;
        }
        if (StringUtils.isEmpty(password)) {
            response.getWriter().write("密码不能为空");
            return;
        }
        try {
            //2调用业务层逻辑
            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);
            //3转发重定向
            if (user != null) {//如果用户存在，
                HttpSession session = request.getSession();//请求得到对象域
                session.setAttribute("user", user);//对象域设置属性  user user中得数据

                response.sendRedirect("/list");
            } else {//如果用户不存在，登录失败，跳到错误页面
                response.sendRedirect("message.html");
            }
        } catch (Exception e) {
            //3转发重定向
            System.out.println(e.getMessage());//输出异常
            response.sendRedirect("message.html");//跳转到错误页面
        }
    }
}

